// 简易 Node.js + Express 后端，mock 数据接口
const express = require('express')
const app = express()
const port = 3001
const { MongoClient, ObjectId } = require('mongodb')
const mongoUrl = 'mongodb://localhost:27017'
const dbName = 'smartwear'
let db

MongoClient.connect(mongoUrl, { useUnifiedTopology: true })
  .then(client => {
    db = client.db(dbName)
    console.log('MongoDB connected')
  })
  .catch(err => {
    console.error('MongoDB connection error:', err)
  })

// 用户活跃度趋势（user_activity 集合，字段：date, count）
app.get('/api/user/active-trend', async (req, res) => {
  const data = await db.collection('user_activity').find().sort({ date: 1 }).toArray()
  res.json(data)
})
app.post('/api/user/active-trend', async (req, res) => {
  const { date, count } = req.body
  await db.collection('user_activity').insertOne({ date, count })
  res.json({ success: true })
})

// 年龄性别分布（user_stats 集合，字段：age, male, female）
app.get('/api/user/age-gender-distribution', async (req, res) => {
  const data = await db.collection('user_stats').find({ type: 'age-gender' }).toArray()
  res.json(data)
})
app.post('/api/user/age-gender-distribution', async (req, res) => {
  const { age, male, female } = req.body
  await db.collection('user_stats').insertOne({ type: 'age-gender', age, male, female })
  res.json({ success: true })
})

// 用户满意度趋势（user_stats 集合，字段：month, score）
app.get('/api/user/satisfaction-trend', async (req, res) => {
  const data = await db.collection('user_stats').find({ type: 'satisfaction' }).sort({ month: 1 }).toArray()
  res.json(data)
})
app.post('/api/user/satisfaction-trend', async (req, res) => {
  const { month, score } = req.body
  await db.collection('user_stats').insertOne({ type: 'satisfaction', month, score })
  res.json({ success: true })
})

// 最近报警
app.get('/api/alarm/recent', (req, res) => {
  res.json([
    { level: 'high', title: '电池电量过低', desc: 'ID: 8723，位于上海，电量低于10%', time: '10分钟前' },
    { level: 'medium', title: '传感器读数异常', desc: 'ID: 5432，位于北京，心率传感器异常', time: '35分钟前' },
    { level: 'low', title: '同步失败', desc: 'ID: 9078，位于广州，数据同步失败', time: '2小时前' },
  ])
})

// 总览数据接口
app.get('/api/overview', (req, res) => {
  res.json({
    totalUsers: 1320,
    activeDevices: 1050,
    avgUsage: 42,
    needMaintenance: 53,
    userGrowth: 6.2 // 新增字段，单位为百分比
  })
})

// 设备状态分布
app.get('/api/device/status-distribution', (req, res) => {
  res.json({
    normal: 82,
    minor: 12,
    maintenance: 5,
    offline: 1
  })
})

app.use(express.json())

// 用户管理
app.get('/api/user/list', async (req, res) => {
  const users = await db.collection('users').find().toArray()
  res.json(users)
})
app.post('/api/user/add', async (req, res) => {
  const { username, email, role, active, openid, gender, age, satisfaction } = req.body
  const user = { username, email, role, active, openid, gender, age, satisfaction }
  const result = await db.collection('users').insertOne(user)
  user._id = result.insertedId
  res.json({ success: true, user })
})
app.post('/api/user/update', async (req, res) => {
  const { id, username, email, role, active, openid, gender, age, satisfaction } = req.body
  const updateFields = { username, email, role, active, openid, gender, age, satisfaction }
  // 移除 undefined 字段，避免覆盖已有数据
  Object.keys(updateFields).forEach(key => updateFields[key] === undefined && delete updateFields[key])
  const result = await db.collection('users').updateOne({ _id: new ObjectId(id) }, { $set: updateFields })
  if (result.matchedCount) {
    res.json({ success: true })
  } else {
    res.status(404).json({ success: false, msg: '用户不存在' })
  }
})
app.post('/api/user/delete', async (req, res) => {
  const { id } = req.body
  await db.collection('users').deleteOne({ _id: new ObjectId(id) })
  res.json({ success: true })
})

// 管理后台用户管理接口（admin_users 集合）
app.get('/api/admin/user/list', async (req, res) => {
  const users = await db.collection('admin_users').find().toArray()
  res.json(users)
})
app.post('/api/admin/user/add', async (req, res) => {
  const { username, email, role, active, password } = req.body
  const user = { username, email, role, active, password }
  const result = await db.collection('admin_users').insertOne(user)
  user._id = result.insertedId
  res.json({ success: true, user })
})
app.post('/api/admin/user/update', async (req, res) => {
  const { id, username, email, role, active, password } = req.body
  const updateFields = { username, email, role, active, password }
  Object.keys(updateFields).forEach(key => updateFields[key] === undefined && delete updateFields[key])
  const result = await db.collection('admin_users').updateOne({ _id: new ObjectId(id) }, { $set: updateFields })
  if (result.matchedCount) {
    res.json({ success: true })
  } else {
    res.status(404).json({ success: false, msg: '用户不存在' })
  }
})
app.post('/api/admin/user/delete', async (req, res) => {
  const { id } = req.body
  await db.collection('admin_users').deleteOne({ _id: new ObjectId(id) })
  res.json({ success: true })
})

// 设备管理
app.get('/api/device/list', async (req, res) => {
  const devices = await db.collection('devices').find().toArray()
  res.json(devices)
})
app.post('/api/device/add', async (req, res) => {
  const { id } = req.body
  const exist = await db.collection('devices').findOne({ id })
  if (exist) return res.status(400).json({ success: false, msg: '设备ID已存在' })
  await db.collection('devices').insertOne({ id, status: '离线', bindUser: '' })
  res.json({ success: true })
})
app.post('/api/device/toggle', async (req, res) => {
  const { id } = req.body
  const device = await db.collection('devices').findOne({ id })
  if (!device) return res.status(404).json({ success: false, msg: '设备不存在' })
  const newStatus = device.status === '在线' ? '离线' : '在线'
  await db.collection('devices').updateOne({ id }, { $set: { status: newStatus } })
  res.json({ success: true, status: newStatus })
})
app.post('/api/device/unbind', async (req, res) => {
  const { id } = req.body
  await db.collection('devices').deleteOne({ id })
  res.json({ success: true })
})

// 数据分析
app.get('/api/analysis/user-growth', async (req, res) => {
  const data = await db.collection('analysis').find({ type: 'user-growth' }).sort({ date: 1 }).toArray()
  res.json(data)
})
app.post('/api/analysis/user-growth', async (req, res) => {
  const { date, count } = req.body
  await db.collection('analysis').insertOne({ type: 'user-growth', date, count })
  res.json({ success: true })
})
app.get('/api/analysis/device-active', async (req, res) => {
  const data = await db.collection('analysis').find({ type: 'device-active' }).sort({ date: 1 }).toArray()
  res.json(data)
})
app.post('/api/analysis/device-active', async (req, res) => {
  const { date, count } = req.body
  await db.collection('analysis').insertOne({ type: 'device-active', date, count })
  res.json({ success: true })
})

// 经销商营业额
app.get('/api/dealer/sales', async (req, res) => {
  const data = await db.collection('dealer_sales').find({ type: 'sales' }).toArray()
  res.json(data)
})
app.post('/api/dealer/sales', async (req, res) => {
  const { name, amount, growth } = req.body
  await db.collection('dealer_sales').insertOne({ type: 'sales', name, amount, growth })
  res.json({ success: true })
})
app.get('/api/dealer/sales-trend', async (req, res) => {
  const data = await db.collection('dealer_sales').find({ type: 'sales-trend' }).sort({ month: 1 }).toArray()
  res.json(data)
})
app.post('/api/dealer/sales-trend', async (req, res) => {
  const { month, amount } = req.body
  await db.collection('dealer_sales').insertOne({ type: 'sales-trend', month, amount })
  res.json({ success: true })
})

// 系统监控检测接口
app.get('/api/system/check', (req, res) => {
  // 这里可接入真实检测逻辑，当前为模拟
  setTimeout(() => {
    const serverStatus = Math.random() > 0.1 ? '正常' : '异常'
    const dbStatus = Math.random() > 0.1 ? '正常' : '异常'
    const apiStatus = Math.random() > 0.1 ? '正常' : '异常'
    const alarmInfo = (serverStatus === '异常' || dbStatus === '异常' || apiStatus === '异常') ? '发现异常，请检查！' : '无'
    res.json({ serverStatus, dbStatus, apiStatus, alarmInfo })
  }, 1000)
})

app.listen(port, () => {
  console.log(`Mock API server running at http://localhost:${port}`)
})
